package com.kongge.viewdisplayframeworklib.ui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.kongge.viewdisplayframeworklib.R;

import java.util.List;

/**
 * author:kongge
 * date:2018/9/12
 * layout:
 * description:
 */

public class Tabbar extends RelativeLayout {

    private List<String> titleList;


    private LinearLayout llContainer;

    private int curSelectedIndex;

    private OnTabbarSelectChangeListener onTabbarSelectChangeListener;

    public Tabbar(Context context) {
        super(context);
    }

    public Tabbar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        llContainer = findViewById(R.id.ll_container);
    }

    public void setTitleList(List<String> list) {
        if (list == null) {
            return;
        }
        this.titleList = list;
        llContainer.removeAllViews();
        for (int i = 0; i < list.size(); i++) {
            View view = createView(list.get(i), i);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1);
            llContainer.addView(view, layoutParams);
        }
        setSelectedIndex(0);
    }

    public void setSelectedIndex(int index) {
        if (index < 0 || index >= llContainer.getChildCount()) {
            return;
        }
        curSelectedIndex = index;
        for (int i = 0; i < llContainer.getChildCount(); i++) {
            TabbarItemView tabbarItemView = (TabbarItemView) llContainer.getChildAt(i);
            tabbarItemView.setSelected(i == index);
        }
    }

    public void setOnTabbarSelectChangeListener(OnTabbarSelectChangeListener onTabbarSelectChangeListener) {
        this.onTabbarSelectChangeListener = onTabbarSelectChangeListener;
    }

    private View createView(String title, final int index) {
        TabbarItemView tabbarItemView = (TabbarItemView) LayoutInflater.from(getContext()).inflate(R.layout.pagequeue_tabbar_item, null);
        tabbarItemView.setTitle(title);
        tabbarItemView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                int oldSelectIndex = curSelectedIndex;
                setSelectedIndex(index);
                if (onTabbarSelectChangeListener != null) {
                    onTabbarSelectChangeListener.onHorizontalScrollTabbarSelectChange(Tabbar.this, oldSelectIndex, curSelectedIndex);
                }
            }
        });
        return tabbarItemView;
    }

    public interface OnTabbarSelectChangeListener {
        void onHorizontalScrollTabbarSelectChange(View view, int oldIndex, int curIndex);
    }
}
